#!/usr/bin/env python
########################################################################
#  Quote - On-line historical quotes
#  Copyright (C) 2007,8 Ehud Ben-Reuven
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
########################################################################
"""Retrieve historical FX from www.oanda.com """
import urllib
import quote

def get(ticker, d1, d2):
    if not (len(ticker)==8 and ticker.endswith('=X')):
        raise Exception('Illegal FX rate ticker')
    quote.info("oanda.get(%s, %s, %s)", ticker, d1, d2)
    cur1=ticker[0:3]
    cur2=ticker[3:6]
    def yyyymmdd2mmddyy(d):
        return d[4:6]+'/'+d[6:8]+'/'+d[2:4]
    def mmddyy2yyyymmdd(d):
        if len(d)!=10 or d[2]!='/' or d[5]!='/':
            raise Exception('Illegal date format')
        return d[6:10]+d[0:2]+d[3:5]
    d1=yyyymmdd2mmddyy(d1)
    d2=yyyymmdd2mmddyy(d2)
    url = 'http://www.oanda.com/convert/fxhistory'
    query = (
        ('lang','en'),
        ('date1',d1),
        ('date',d2),
        ('date_fmt','us'),
        ('exch',cur1),
        ('exch2',''),
        ('expr',cur2),
        ('expr2',''),
        ('margin_fixed','0'),
        ('SUBMIT','Get Table'),
        ('format','CSV'),
        ('redirected','1')
        )
    page = urllib.urlopen(url+'?'+urllib.urlencode(query)).read().splitlines()
    table=False
    result={}
    for l in page:
        if l.startswith('<PRE>'):
                table=True
                l=l[5:]
        elif l.startswith('</PRE>'):
                table=False
        if table:
            l=l.split(',')
            date=mmddyy2yyyymmdd(l[0])
            result[date] = {'rate':l[1]}
    return result

